package com.bgck.chatedemo;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.LinkedList;

public class MainActivity extends AppCompatActivity {

    private ChatAdapter adapter;
    private Handler mainHandler = new Handler(Looper.getMainLooper());
    private int messageCount = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        adapter = new ChatAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);

        startMessageSimulation();
    }

    private void startMessageSimulation() {
        new Thread(() -> {
            while (messageCount <= 5) { // 测试5条消息
                try {
                    Thread.sleep(50);
                    final String content = "消息" + messageCount + "：" + generateRandomText();
                    mainHandler.post(() -> adapter.addNewMessage(content));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                messageCount++;
            }
        }).start();
    }

    private String generateRandomText() {
        // 生成10个随机汉字
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 10; i++) {
            sb.append((char) (0x4e00 + (int) (Math.random() * 100)));
        }
        return sb.toString();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        adapter.cleanup();
    }

    static class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.MessageViewHolder> {
        private final LinkedList<Message> messageQueue = new LinkedList<>();
        private final StringBuilder fullContent = new StringBuilder();
        private int currentProgress = 0;
        private ValueAnimator currentAnimator;
        private final Handler handler = new Handler(Looper.getMainLooper());

        static class Message {
            final String content;
            final int startPos;
            final int endPos;
            boolean isThinking;

            Message(String content, int start) {
//                this.content = content + "\n"; // 每条消息换行
                this.content = content + " pppp "; // 每条消息换行
                this.startPos = start;
                this.endPos = start + this.content.length();
            }
        }

        void addNewMessage(String content) {
            handler.post(() -> {
                // 记录新消息位置
                int start = fullContent.length();
                Message newMsg = new Message(content, start);
                fullContent.append(newMsg.content);

                messageQueue.offer(newMsg);

                if (currentAnimator == null || !currentAnimator.isRunning()) {
                    processNextMessage();
                } else {
                    // 立即完成当前显示
                    currentAnimator.end();
                }
            });
        }

        private void processNextMessage() {
            if (!messageQueue.isEmpty()) {
                Message msg = messageQueue.poll();
                startTypingAnimation(msg);
            }
        }

        private void startTypingAnimation(Message msg) {
            if (currentAnimator != null) {
                currentAnimator.cancel();
            }

            currentAnimator = ValueAnimator.ofInt(currentProgress, msg.endPos);
            currentAnimator.setDuration(100 * (msg.endPos - currentProgress));

            currentAnimator.addUpdateListener(anim -> {
                currentProgress = (int) anim.getAnimatedValue();
                notifyItemChanged(0);
            });

            currentAnimator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    currentProgress = msg.endPos;
                    processNextMessage();
                }
            });

            currentAnimator.start();
        }

        @Override
        public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            TextView textView = new TextView(parent.getContext());
            textView.setTextSize(16);
            textView.setTextColor(0xFF333333);
            textView.setPadding(50, 30, 50, 30);
            return new MessageViewHolder(textView);
        }

        @Override
        public void onBindViewHolder(MessageViewHolder holder, int position) {
            String displayedText = fullContent.substring(0, currentProgress);
            holder.textView.setText(displayedText);

            // 自动滚动到底部
            holder.textView.post(() -> {
                if (holder.textView.getLayout() != null) {
                    int scrollY = holder.textView.getLayout().getLineTop(holder.textView.getLineCount())
                            - holder.textView.getHeight();
                    holder.textView.scrollTo(0, Math.max(scrollY, 0));
                }
            });
        }

        @Override
        public int getItemCount() {
            return 1; // 固定显示一个Item
        }

        void cleanup() {
            handler.removeCallbacksAndMessages(null);
            if (currentAnimator != null) {
                currentAnimator.cancel();
            }
            messageQueue.clear();
            fullContent.setLength(0);
            currentProgress = 0;
        }

        static class MessageViewHolder extends RecyclerView.ViewHolder {
            final TextView textView;

            MessageViewHolder(TextView itemView) {
                super(itemView);
                textView = itemView;
                textView.setVerticalScrollBarEnabled(true);
            }
        }
    }
}